package com.e7.service;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;

import org.springframework.stereotype.Service;

import com.e7.util.Captchar;
import com.e7.util.Encoder;
import com.opensymphony.xwork2.ActionContext;

@Service("captchaService")
public class CaptchaService {
	Captchar captchar = new Captchar();

	public InputStream generate(String seed) throws IOException {
		String captcha = Encoder.encode(System.currentTimeMillis() + "C")
				.substring(0, 4);
		ActionContext.getContext().getSession().put("captcha", captcha);
		return this.generate(0, 0, captcha);
	}

	public InputStream generate(int width, int height, String captcha)
			throws IOException {
		this.captchar.setCaptcha(captcha);
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		ImageOutputStream imageOut = ImageIO.createImageOutputStream(output);
		this.captchar.writeTo(imageOut);
		imageOut.close();
		return new ByteArrayInputStream(output.toByteArray());
	}
}